<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="物料字典">
            <el-input
              v-model="filterText"
              placeholder="输入关键字进行过滤"
              style="background: whitesmoke"
            />
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="height: 200px"
            >
              <el-tree
                ref="treeRef"
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.materialName]
                    : []
                "
                class="tree-border"
                :data="state.bomDOptions"
                :props="defaultProps"
                node-key="code"
                show-checkbox
                @check="handleCheckChange"
                :filter-node-method="filterNode"
              />
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="物料名称" prop="materialName">
            <el-input
              v-model="baTable.form.items!.materialName"
              placeholder="请输入物料名称"
            />
          </el-form-item>
          <el-form-item label="物料类型" prop="materialType">
            <el-select
              v-model="baTable.form.items!.materialType"
              placeholder="请选择物料类型"
            >
              <el-option
                v-for="item in state.materialTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应用领域" prop="application">
            <el-tree-select
              v-model="baTable.form.items!.application"
              :data="state.applicationAreaOptions"
              check-strictly
              :props="{
                label: 'dictLabel',
                value: 'dictValue',
                children: 'children',
              }"
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item prop="supplierName" label="供应商名称">
            <el-input
              v-model="baTable.form.items!.supplierName"
              type="string"
              placeholder="供应商名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="未含税单价" prop="unitPriceWithoutTax">
            <el-input-number
              v-model="baTable.form.items!.unitPriceWithoutTax"
            />
          </el-form-item>
          <el-form-item label="税率" prop="taxRate">
            <el-input-number
              v-model="baTable.form.items!.taxRate"
              @blur="getTaxUnitPrice"
            />
          </el-form-item>
          <el-form-item label="含税单价" prop="taxUnitPrice">
            <el-input-number v-model="baTable.form.items!.taxUnitPrice" />
          </el-form-item>
          <el-form-item label="产品描述" prop="remark">
            <el-input
              v-model="baTable.form.items!.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="产品描述"
            />
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, inject, onMounted, watch, nextTick } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useRegion } from "@/store/backend/SysM/region";
import { getPointByAddress } from "vue-baidu-map-3x"; //baidu-map组件red
import { getDictData } from "@/utils/common"; // 导入表格api方法生成器
import { ElNotification } from "element-plus"; //处理导航信息

const formRef = ref<InstanceType<typeof ElForm>>();
const baTable = inject("baTable") as baTableClass;
const dictionary = inject("dictionary") as any;
const business = useBusiness();
const region = useRegion();
const treeRef = ref<InstanceType<typeof ElTree>>();
const bomD = inject("bomD") as any;
const supplier = inject("supplier") as any;
const filterText = ref(""); //物料关键词过滤

const state: {
  regionOptions: anyObj[];
  supplierTypeOptions: anyObj[];
  supplierOptions: anyObj[];
  bomDOptions: anyObj[];
  applicationAreaOptions: anyObj[];
  materialTypeOptions: anyObj[];
} = reactive({
  regionOptions: [], //区域列表
  supplierTypeOptions: [], //供应商类型列表
  supplierOptions: [], //供应商列表
  bomDOptions: [], //bom字典列表
  applicationAreaOptions: [], //应用领域列表
  materialTypeOptions: [], //物料类型列表
});

//物料树形结构
const defaultProps = {
  children: "children",
  label: "name",
};
// 物料关键词过滤
const filterNode = (value: string, data: any) => {
  console.log(value, data);

  if (!value) return true;
  return data.name.includes(value);
};

const props = {
  label: "areaName",
  value: "areaId",
  children: "children",
};

const rules = reactive<FormRules>({
  supplierName: [
    { required: true, message: "供应商名称不能为空", trigger: "blur" },
  ],
  materialName: [
    { required: true, message: "物料名称不能为空", trigger: "blur" },
  ],
  materialType: [
    { required: true, message: "物料型号不能为空", trigger: "blur" },
  ],
  application: [
    { required: true, message: "应用领域不能为空", trigger: "blur" },
  ],
  supplierType: [
    { required: true, message: "供应商类型不能为空", trigger: "blur" },
  ],
  supplierStatus: [
    { required: true, message: "供应商状态不能为空", trigger: "blur" },
  ],
  taxRate: [{ required: true, message: "税率不能为空", trigger: "blur" }],
  unitPriceWithoutTax: [
    { required: true, message: "未含税单价不能为空", trigger: "blur" },
  ],
  taxUnitPrice: [
    { required: true, message: "含税单价不能为空", trigger: "blur" },
  ],
});

const handleCheckChange = (data: any, node: any) => {
  console.log("data", data, "node", node);
  baTable.form.items!.materialName = data.name;
  baTable.form.items!.materialType = data.type;
};
//换算含税单价
const getTaxUnitPrice = () => {
  baTable.form.items!.taxUnitPrice =
    baTable.form.items!.unitPriceWithoutTax -
    baTable.form.items!.unitPriceWithoutTax *
      (baTable.form.items!.taxRate / 100);
};

//包含所有的层级id
const getCheckeds = () => {
  return treeRef
    .value!.getCheckedKeys()
    .concat(treeRef.value!.getHalfCheckedKeys());
};
//获取最后一级id
const getCheckedOne = () => {
  return treeRef.value!.getCheckedKeys();
};

//应用领域字典
const getMenuStatus = () => {
  //应用领域
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["application"])
  ) {
    dictionary.getDictInfo("sys_application_area").then((res: any) => {
      dictionary.moreTags["application"] = getDictData(res);
      dictionary.moreTags["applicationOrigin"] = res;
    });
  } else {
    state.applicationAreaOptions = dictionary.moreTags["applicationOrigin"];
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["materialType"])
  ) {
    dictionary.getDictInfo("sys_bomdict_type").then((res: any) => {
      dictionary.moreTags["materialType"] = getDictData(res);
      dictionary.moreTags["materialTypeOrigin"] = res;
      state.materialTypeOptions = res;
      console.log("获取物料类型的字典", state.materialTypeOptions);
    });
  } else {
    state.materialTypeOptions = dictionary.moreTags["materialTypeOrigin"];
    console.log("获取物料类型的字典", state.materialTypeOptions);
  }
};
//获取应用领域字典
getMenuStatus();

onMounted(() => {
  //获取物料字典数据
  bomD.getBomDictByRole().then((res: any) => {
    state.bomDOptions = res;
  });
  setTimeout(() => {
    baTable.form.items!.supplierName = supplier.info.supplierName; //供应商名称
    baTable.form.items!.supplierId = supplier.info.supplierId; //供应商ID
  });
});

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});

defineExpose({
  getCheckeds,
  getCheckedOne,
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.tree-border {
  width: 100%;
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  // background: #fff none;
  border-radius: 4px;
}
</style>
